// pages/shop/shop.js

// import {
//     showToast
// } from "../../utils/util"; //调用公式方法
import {
    postcreate, unifiedorder, getchkOrder
} from '../request/api.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        cart: [],
        totalNum: 0,
        address: {} //存储收货地址,
    },
    //增加
    add(e) {
        // console.log(113, e);  
        let index = e.currentTarget.dataset.index
        let { cart, totalPrice, allChecked } = this.data
        cart[index].num++
        //调用公用方法
        this.setCart(cart)
    },
    //减少-点击减时，小于1时，弹出确认框，确定后删除当前行
    minus(e) {
        let index = e.currentTarget.dataset.index
        let { cart, totalPrice, allChecked } = this.data
        //1.取反
        if (cart[index].num > 1) {
            cart[index].num--
        } else {
            return false
        }
        //调用公用方法
        this.setCart(cart)
    },
    setCart(cart) {
        let totalPrice = 0, allChecked = true, allnum = 0;
        //如果所有单选都选中，就全选，除非有一个，全选就不选中。计算总价方法是全局变量
        cart.forEach(item => {
            //已经勾选的计算总价
            if (item.checked == true) {
                totalPrice += (item.goods_price * item.num) + ''
                allnum += item.num
            }
            else {
                allChecked = false
            }
        })
        this.setData({
            cart,
            totalPrice,
            allChecked,
            allnum

        })
        wx.setStorageSync('cart', cart)

    },
    handleItemAllCheck() {
        let { cart, totalPrice, allChecked } = this.data
        allChecked = !allChecked
        cart.forEach(item => {
            item.checked = allChecked
        })
        this.setCart(cart)
    },
    //点击结算-判断收货地址是否有值,购物车是否有值
    async handlePay() {
        let token = wx.getStorageSync('token')
        if (!token) {
            wx.showToast({
                title: '请登录',
            })
            return
        }
        // 1 判断收货地址
        const {
            address,
            totalPrice
        } = this.data;
        if (!address.userName) {
            wx.showToast({
                title: '请选择收货地址',
            })
            //可以把公共常用的方法，提炼出去，用promise封装下
            // await showToast({title:"您还没有选择收货地址"});
            return;
        }
        // 2 判断用户有没有选购商品
        if (totalPrice === 0) {
            wx.showToast({
                title: "您还没有选购商品"
            });
            return;
        }

        let { addressInfo, cart, Price } = this.data
        let arr = []
        cart.forEach(item => {
            arr.push({
                "goods_id": item.goods_id,
                "goods_number": item.num,
                "goods_price": item.goods_price
            })
            console.log(arr, 110);
        })
        let res = await postcreate({ order_price: totalPrice, consignee_addr: address.all, goods: arr })
        console.log(res);
        if (res.meta.status == 200) {
            let order_number = res.message.order_number
            let err = await unifiedorder({ order_number: order_number })
            console.log(err);
            if (err.meta.status == 200) {
                let { pay } = err.message
                wx.requestPayment({
                    ...pay,
                    success(res) {
                        console.log(res, '成功');
                    },
                    fail(res) {
                        console.log(res, '失败');
                    }
                })
            }
            let ress = await getchkOrder({ order_number: order_number })
            console.log(ress);
        }


    },


    onChange(e) {
        let index = e.currentTarget.dataset.index
        let { cart } = this.data
        cart[index].checked = !cart[index].checked
        this.setCart(cart)

    },
    //咱们这里自己写死的收货地址
    handleChooseAddress2() {
        let address = {};
        address.all = '北京市海淀区清华大学2号楼'
        address.telNumber = '13466688888'
        address.userName = '范范'
        wx.setStorageSync('address', address)
        this.setData({
            address
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let cart = wx.getStorageSync('cart') || []
        this.setCart(cart)
        let address = wx.getStorageSync('address')
        this.setData({
            address
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})